﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Prompts.ReportCatalog.Model
{
    [ServiceContract(
        ConfigurationName = "SilverlightApplication1.ServiceReference1.IReportCatalogService")]
    public interface IReportCatalogService
    {
        [OperationContract(
            AsyncPattern = true,
            Action = "http://tempuri.org/IReportCatalogService/GetReportCatalogInfo",
            ReplyAction = "http://tempuri.org/IReportCatalogService/GetReportCatalogInfoResponse")]
        
        IAsyncResult BeginGetReportCatalogInfo(AsyncCallback callback, object asyncState);
        ReportCatalogInfo EndGetReportCatalogInfo(IAsyncResult result);
    }

    public class ReportCatalogServiceClient : ClientBase<IReportCatalogService>, IReportCatalogServiceClient
    {
        public ReportCatalogServiceClient(Binding binding, EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
        {
        }

        public void GetReportCatalogInfoAsync(Action<ReportCatalogInfo> callBack)
        {
            InvokeAsync(
                (inValues, callback, asyncState) => Channel.BeginGetReportCatalogInfo(callback, asyncState), 
                null, 
                OnEndOperationDelegate,
                state =>
                    {
                        var e = (InvokeAsyncCompletedEventArgs)state;
                        var catalogInfo = (ReportCatalogInfo)e.Results[0];
                        callBack(catalogInfo);
                    }, 
                new object());
        }

        private object[] OnEndOperationDelegate(IAsyncResult result)
        {
            try
            {
                var retVal = Channel.EndGetReportCatalogInfo(result);
                return new object[] {retVal};
            }
            catch (Exception e)
            {
                return new object[] {new ReportCatalogInfo {ErrorMessage = e.Message, ErrorOccured = true}};
            }
        }
    }
}